//
//  DatabaseHelper.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 3/2/13.
//  Copyright (c) 2013 GOPI. All rights reserved.
//

#import "DatabaseHelper.h"
#import "Search+Search.h"



@implementation DatabaseHelper

static UIManagedDocument * database;

+ (NSString *) getDatabaseName {
    
    NSString *databaseName = [[Search getUrlForDatabase] lastPathComponent];
    
    return databaseName;
}
+ (UIManagedDocument *) database:(NSString *) databaseName {
    
  
    if (databaseName != nil)
        return [[UIManagedDocument alloc] initWithFileURL:[NSURL URLWithString:databaseName]];
    else
        return [[UIManagedDocument alloc] initWithFileURL:[Search getUrlForDatabase]];
    
}

+ (UIManagedDocument *) database
{
    return database;
}
+ (void) updateDatabase:(NSString *) databaseName
             usingBlock:(generic_block_t) block
{
    [self openDatabase:[self getDatabaseName]
                reopen:NO
            usingBlock:^(UIManagedDocument *database) {
        [database saveToURL:database.fileURL forSaveOperation:UIDocumentSaveForOverwriting
          completionHandler:^(BOOL success) {
              block();
          }];
    }];
}
+ (void) openDatabase:(NSString *) databaseName
               reopen:(BOOL) reopen
           usingBlock:(completion_block_t) block
{
   
    if (database && !reopen)
        block(database);
    else
    {
        database = [self database:databaseName];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:[database.fileURL path]]) {
            [database saveToURL:database.fileURL
               forSaveOperation:UIDocumentSaveForCreating
              completionHandler:^(BOOL success) {
                  block(database);
              }];
            
        } else if (database.documentState == UIDocumentStateClosed) {
            [database  openWithCompletionHandler:^(BOOL success) {
                block(database);
            }];
        } else if (database.documentState == UIDocumentStateNormal) {
            block(database);
        }
    }
}
@end
